package com.persagy.demo;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@ServerEndpoint("/test")
@Component
@Slf4j
public class MyWebsocketServer {
	/**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();
    
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("有新的客户端连接了: " + session.getId());
        //将新用户存入在线的组
        clients.put(session.getId(), session);
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("客户端断, id为:" + session.getId());
        //将掉线的用户移除在线的组里
        clients.remove(session.getId());
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message, Session session) {
    	String clientId = session.getId();
        System.out.println("收到客户端"+clientId+"的消息: " + message);
        System.out.println("启动给客户端"+clientId+"的发消息线程");
        sendMsgToClient(clientId);
    }
    
    /**
     * 给客户端发消息
     * @param clientId
     */
    private void sendMsgToClient(String clientId) {
    	if(clients.keySet().contains(clientId)) {
    		new Thread("send-msg-to-client"+clientId){
    			@Override
    			public void run() {
    				while(clients.keySet().contains(clientId)) {
    					String msg = TestDataFactory.getData();
    					clients.get(clientId).getAsyncRemote().sendText(msg);
    					
    					try {
    						// 每0.5s发一次数
							Thread.sleep(1000L);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
    				}
    			}
    		}.start();
    	}
    }
    

    /**
     * 群发消息
     * @param message 消息内容
     */
    private void sendAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            sessionEntry.getValue().getAsyncRemote().sendText(message);
        }
    }
}
